import { ref, unref, Ref } from 'vue';
import { message } from 'ant-design-vue';
import { getListApiObj } from '@/config/table';
import { IPagination } from '@/types';
export const useTableData = (setLoading: Fn, paginationConfig: Ref<Partial<IPagination>>, setPaginationConfig: Fn, no: string) => {
    let tableNo = no; // 表格编号
    const list = ref<any>([]);
    const searchQuery = ref<any>({});
    const getList = async () => {
        setLoading(true);
        const { current: pageNum, pageSize } = unref(paginationConfig);
        const { success, moule, totalCount, errorMsg } = await getListApiObj[tableNo]({
            pageNum,
            pageSize,
            ...unref(searchQuery)
        });
        setLoading(false);
        if (success) {
            list.value = moule ? [...moule] : [];
            setPaginationConfig({
                total: totalCount || 0
            });
        } else {
            message.error(errorMsg);
        }
        return { success, moule, totalCount, errorMsg };
    };
    // 设置表格数据
    const setList = (newList) => {
        list.value = [...newList];
    };

    const setTableNo = (no: string) => {
        tableNo = no;
    };

    // 分页查询
    const handleTableChange = (pagination: any, filters: any, sorter: any) => {
        const { pageSize, current } = pagination;
        setPaginationConfig({
            current,
            pageSize
        });
        // 是否点击排序
        if (sorter && sorter.field) {
            setSearchQuery({
                sortColumn: sorter.field,
                sortRole: sorter.order === 'ascend' ? 'asc' : 'desc'
            });
        }
        if (filters) {
            const query = {};
            Object.keys(filters).forEach((key) => {
                query[key] = filters[key].join(',');
            });
            setSearchQuery({
                ...query
            });
        }
        getList();
    };
    // 设置查询参数
    const setSearchQuery = (query) => {
        searchQuery.value = {
            ...searchQuery.value,
            ...query
        };
    };
    const clearSearchQuery = () => {
        searchQuery.value = {};
    };

    return {
        list,
        searchQuery,
        getList,
        setList,
        handleTableChange,
        setSearchQuery,
        clearSearchQuery,
        setTableNo
    };
};